import { _decorator, Component, EditBox, Label, log, Node, ScrollView } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('WebSoketScript')
export class WebSoketScript extends Component {
    
    @property(EditBox)
    private textNode: EditBox = null;

    @property(Label)
    private ChatFrame: Label = null;

    @property(ScrollView)
    private scrollView: ScrollView = null;
    
    private socket: WebSocket = null;
    
    start() {
        this.ChatFrame.getComponent(Label).string = '';
        let self = this;

        // 创建WebSocket实例，URL应替换为实际服务器地址
        this.socket = new WebSocket('ws://127.0.0.1:7777/websocket');

        // 当WebSocket连接打开时触发
        this.socket.onopen = function(event) {
            console.log("WebSocket connection opened.");
            
            // 发送自定义协议的消息示例
            var customMessage = {
                type: 'private',
                from: 'user1',
                to: 'user2',
                content: 'Hello, this is a private message!'
            };
            
            for (let i = 0; i < 1; i++) {
                self.socket.send(JSON.stringify(customMessage));
            }
        };

        // 当接收到服务器消息时触发
        this.socket.onmessage = function(event) {
            var message = JSON.parse(event.data); // 将接收到的字符串转换为JSON对象
            log("Received message:", message, message.type);
            switch (message.type) {
                case 'private':
                    self.handlePrivateMessage(message);
                    break;
                case 'group':
                    self.handleGroupMessage(message);
                    break;
                // 其他类型的处理...
            }
        };

        // 当WebSocket连接关闭时触发
        this.socket.onclose = function(event) {
            if (event.wasClean) {
                console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
            } else {
                // e.g. server process killed or network down
                // event.code is usually 1006 in this case
                console.log('[close] Connection died');
            }
        };

        // 当发生错误时触发
        this.socket.onerror = function(error) {
            console.error("WebSocket error observed:", error);
        };

        
        
    }

    update(deltaTime: number) {
        
    }

    // 自定义函数处理私聊消息
    handlePrivateMessage(message) {
        console.log(`Received private message from ${message.from}: ${message.content}`);
        this.ChatFrame.getComponent(Label).string += '\n' + message.content;
    }

    // 自定义函数处理群聊消息
    handleGroupMessage(message) {
        console.log(`Received group message: ${message.content}`);
    }

    sendMessage() {
        if (this.socket.readyState === WebSocket.OPEN) {
            let message = this.textNode.getComponent(EditBox).string;
            log("发送消息：" + message);

            var customMessage = {
                type: 'private',
                from: 'user1',
                to: 'user2',
                content: message
            };
            this.socket.send(JSON.stringify(customMessage));
            this.scrollView.scrollToBottom(0.2);
        }
    }
}


